package com.utils;

import com.aliyun.oss.OSSClient;
import com.las.bot.common.Constant;
import com.las.utils.DownImgUtil;
import org.apache.log4j.Logger;

import java.io.File;

public class DownFileUtils {

    private static Logger logger = Logger.getLogger(DownFileUtils.class);

    public static File getFile(String sourceUrl){
        String objectName = IdUtil.nextId();
        String path = System.getProperty("user.dir");
        logger.info("下载文件到项目本地路径：" + path);
        File file = null;
        try {
            String fileUrl = DownImgUtil.downLoadFromUrl(sourceUrl, objectName, path);
            file = new File(fileUrl);
//            String endpoint = Constant.HTTPS + Constant.OSS;
//            String accessKeyId = Constant.BUCKET_ID;
//            String accessKeySecret = Constant.BUCKET_KEY;
//            String bucketName = Constant.BUCKET_NAME;
//            // 上传到阿里云OSS
//            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//            ossClient.putObject(bucketName, objectName, file);
//            ossClient.shutdown();
//            // 生成model调用接口保存到远端数据库
//            String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    public static String upFileAndDel(File file,String suffix){
        String imgUrl = "";
        String objectName = IdUtil.nextId() + suffix;
        String path = System.getProperty("user.dir");
        logger.info("上传项目本地路径：" + path);
        try {
            String endpoint = Constant.HTTPS + Constant.OSS;
            String accessKeyId = Constant.BUCKET_ID;
            String accessKeySecret = Constant.BUCKET_KEY;
            String bucketName = Constant.BUCKET_NAME;
            // 上传到阿里云OSS
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, file);
            ossClient.shutdown();
            imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(file.exists()){
                file.delete();
            }
        }
        return imgUrl;
    }

}
